import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/data/product_group_entity.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';

import '../controllers/add_device_controller.dart';

class AddDeviceView extends GetView<AddDeviceController> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        BlueService.share.isAdd = false;
        return Future.value(true);
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            LocaleKeys.add_devices_title.tr,
          ),
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          elevation: 1,
          shadowColor: MColor.xFFCCCCCC.withAlpha(80),
        ),
        body: SafeArea(
          bottom: false,
          child: Container(
            width: double.infinity,
            color: MColor.xFFF2F2F2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _topView,
                _scanView,
                Expanded(
                  child: Obx(() {
                    final devices = controller.blueDevices.value;
                    final products = controller.devicesGroup.value;

                    return ListView.builder(
                      itemCount: products.length + 1,
                      itemBuilder: (ctx, index) {
                        if (index == 0) {
                          if (devices.isEmpty) {
                            return Container();
                          }
                          return _lampView(index, devices);
                        } else {
                          final devices = products[index - 1];
                          if (devices.productVos == null || devices.productVos!.isEmpty) {
                            return Container();
                          }
                          return _lampView(index, devices);
                        }
                      },
                    );
                  }),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  get _topView {
    return Container(
      margin: EdgeInsets.only(left: 12, right: 12, top: 16, bottom: 30),
      child: Text(
        LocaleKeys.add_devices_scan_desc.tr,
        style: MFont.regular13.apply(color: MColor.xFF666666),
        textAlign: TextAlign.left,
      ),
    );
  }

  get _scanView {
    return Container(
      margin: EdgeInsets.only(bottom: 16),
      child: Center(
        child: Obx(() {
          final run = BlueService.share.isScaning.value;

          return AnimationView(run);
        }),
      ),
    );
  }

  Widget _lampView(int index, dynamic devices) {
    final isAvail = index == 0;
    final width = (GlobalConst.screenWidth - (isAvail ? 10 : 24)) / 4;
    final height = 90;

    var title = '';
    if (isAvail) {
      title = LocaleKeys.add_devices_available.tr;
    } else {
      title = controller.devicesGroup[index - 1].productGroupName ?? '';
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: EdgeInsets.only(
            left: 12,
            top: 24,
            bottom: isAvail ? 0 : 8,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                style: MFont.regular15.apply(color: MColor.xFF333333),
              ),
              if (isAvail) ...{
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 12),
                    child: Divider(height: 1, color: MColor.xFF999999),
                  ),
                ),
              },
            ],
          ),
        ),
        Container(
          decoration: BoxDecoration(
            color: isAvail ? Colors.transparent : Colors.white,
            borderRadius: BorderRadius.circular(15),
          ),
          margin:
              isAvail ? EdgeInsets.symmetric(horizontal: 5) : EdgeInsets.symmetric(horizontal: 12),
          padding: EdgeInsets.only(bottom: 16),
          child: GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 0,
              crossAxisSpacing: 0,
              childAspectRatio: width / height,
            ),
            itemCount:
                isAvail ? devices.length : (devices as ProductGroupEntity).productVos?.length ?? 0,
            itemBuilder: (ctx, index) {
              return _deviceView(
                index,
                isAvail ? devices[index] : (devices as ProductGroupEntity).productVos![index],
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _deviceView(int index, dynamic device) {
    final available = device is DiscoveredDevice;
    var title = '';
    var urlStrinng = '';
    if (available) {
      final name = (device as DiscoveredDevice).name;
      title = name.split('_').last;
      final pid = name.split('_')[1];
      controller.devicesGroup.forEach((element) {
        element.productVos?.forEach((element) {
          if (pid == element.productCode) {
            urlStrinng = element.productImg ?? '';
            title = element.productName ?? '';
            return;
          }
        });
      });
    } else {
      title = (device as ProductGroupProductVos).productName ?? '';
      urlStrinng = device.productImg ?? '';
    }
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        if (!available) {
          BlueService.share.isAll = true;
          controller.scanDevices(title);
        } else {
          await controller.scanListen?.cancel();
          controller.scanListen = null;
          Get.toNamed(
            Routes.DEVICE_MANAGER,
            arguments: {'group': false, 'add': true, 'device': device},
          )?.then((value) {
            if (value == 0) {
              controller.scanDevices('MZ_MZ');
            }
          });
        }
      },
      child: Container(
        padding: EdgeInsets.only(top: 16),
        child: Column(
          children: [
            urlStrinng.isNotEmpty || !available
                ? CachedNetworkImage(
                    imageUrl: urlStrinng,
                    width: 50,
                    height: 50,
                    placeholder: (ctx, _) {
                      return Container(
                        width: 50,
                        height: 50,
                        decoration: BoxDecoration(
                          color: MColor.xFFCCCCCC,
                          borderRadius: BorderRadius.circular(4),
                        ),
                      );
                    },
                    errorWidget: (ct, x, a) {
                      return Container(
                        width: 50,
                        height: 50,
                        decoration: BoxDecoration(
                          color: MColor.xFFCCCCCC,
                          borderRadius: BorderRadius.circular(4),
                        ),
                      );
                    },
                  )
                : Image.asset(
                    Assets.imagesLightLarge,
                    width: 50,
                    height: 50,
                  ),
            SizedBox(height: 8),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10),
              child: Text(
                title,
                style: available
                    ? MFont.regular11.apply(color: MColor.xFF333333)
                    : MFont.regular11.apply(color: MColor.xFF333333),
                maxLines: 1,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class AnimationView extends StatefulWidget {
  final bool isRun;
  //动画控制器
  AnimationView(this.isRun, {Key? key}) : super(key: key);
  @override
  _AnimationViewState createState() => _AnimationViewState();
}

class _AnimationViewState extends State<AnimationView> with TickerProviderStateMixin {
  AnimationController? controller;
  @override
  void initState() {
    controller = AnimationController(duration: const Duration(seconds: 5), vsync: this);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isRun) {
      controller?.forward();
      controller?.repeat();
    } else {
      controller?.stop();
    }
    return Container(
      child: RotationTransition(
        turns: controller!,
        child: Image.asset(
          Assets.imagesDeviceScan,
          width: 160,
          height: 160,
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
